package Array;

/**
 * @author Vinlee Xiao
 * @Classname CovertNum
 * @Description 字节跳动面试题 核心关键点是如何处理零
 * <p>
 * 输入数字(小于一亿的int),输出中文表示
 * 输入:50321
 * 输出:五万零三百二十一
 * </p>
 * @Date 2022/2/23 10:33
 * @Version 1.0
 */
public class CovertNum {

    static char[] numArr = {'零', '一', '二', '三', '四', '五', '六', '七', '八', '九'};

    static String[] unitArr = {"", "十", "百", "千", "万"};

    /**
     * @param num 要处理的数字
     * @return 返回对应的中文数字
     */
    public static String convertNumToChinese(int num) {
        char[] newNum = String.valueOf(num).toCharArray();
        int len = newNum.length;

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < len; i++) {
            int digit = Integer.parseInt(String.valueOf(newNum[i]));

            if (digit == 0) {
                while (i < len - 1) {
                    if (len - i == 5) {
                        deleteDigit(result);
                        result.append(unitArr[unitArr.length - 1]);
                    }
                    if (newNum[i + 1] != '0') {
                        break;
                    }
                    i++;
                }
                //输出中间的零
                if (i != len - 1) {
                    result.append(numArr[0]);
                }
            } else {
                int index = len - i;
                //如果
                if (index > 4) {
                    index = index - 4;
                }
                result.append(numArr[digit]);
                result.append(unitArr[index - 1]);
                //如果当前位数
                if (len - i == 5) {
                    //进行特殊情况的判断 一十万 --> 十万
                    deleteDigit(result);
                    result.append(unitArr[unitArr.length - 1]);
                }
            }

        }
        return result.toString();
    }

    /**
     * @param result
     */
    public static void deleteDigit(StringBuilder result) {
        int size = result.length();
        if (size >= 2 && result.charAt(size - 1) == '十' && result.charAt(size - 2) == '一') {
            result.deleteCharAt(size - 2);
        }
    }

    public static void main(String[] args) {
        String s = convertNumToChinese(10991020);
        System.out.println(s);
        String s1 = convertNumToChinese(1000);
        System.out.println(s1);
        String s2 = convertNumToChinese(1010);
        System.out.println(s2);
        String s3 = convertNumToChinese(10034);
        System.out.println(s3);
        String s4 = convertNumToChinese(100034);
        System.out.println(s4);
        String s5 = convertNumToChinese(100001);
        System.out.println(s5);
        String s6 = convertNumToChinese(100340);
        System.out.println(s6);
        String s7 = convertNumToChinese(50321);
        System.out.println(s7);
    }

}
